<template>
  <a-spin :spinning="spinning" tip="加载中...">
  <a-card :bordered="false">
    <h3>{{$route.params.id == 'null' ? '新增' : '编辑'}}广告</h3>
    <a-form-model
      ref="rulesForm"
      :model="form"
      :rules="rules"
      :labelCol="{ lg: { span: 6 }, sm: { span: 8 } }"
      :wrapperCol="{ lg: { span: 14 }, sm: { span: 16 } }"
    >
      <a-form-model-item label="投放小程序" prop="weId">
        <a-select v-model="form.weId" placeholder="请选择" show-search :filter-option="filterOption">
          <a-select-option :value="item.weid" v-for="item in brandList" :key="item.weid">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="广告类型" prop="advertisingTypeId">
        <a-select v-model="form.advertisingTypeId" placeholder="请选择" @change="adTypeChange" show-search :filter-option="filterOption">
          <a-select-option v-for="advertisingType in advertisingTypeList" :value="advertisingType.id" :key="advertisingType.id">{{advertisingType.name}}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="跳转方式" prop="jumpWayId">
        <a-select v-model="form.jumpWayId" @change="jumpWayIdChange" :disabled="form.advertisingTypeId==3" placeholder="请选择" show-search :filter-option="filterOption">
          <a-select-option v-for="jumpWay in jumpWayList" :value="jumpWay.id" :key="jumpWay.id">{{jumpWay.name}}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="话题" v-if="form.jumpWayId == 5"  prop="topicId" key="1">
        <a-select v-model="form.topicId"  placeholder="请选择" @change="topicChange" show-search :filter-option="filterOption">
          <a-select-option v-for="topic in topicList" :value="topic.id + ''" :key="topic.id">{{topic.topicName}}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="标题" v-if="form.jumpWayId && form.jumpWayId != 5" prop="title" key="2">
        <a-input
            v-model.trim="form.title"
            placeholder=""
            allowClear
          />
      </a-form-model-item>
      <a-form-model-item v-if="form.jumpWayId==1" label="是否为当前小程序路径" prop="theCurrent" key="3">
        <a-radio-group v-model="form.theCurrent">
          <a-radio :value="0">是</a-radio>
          <a-radio :value="1">否</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item v-if="form.theCurrent ==1 && form.jumpWayId==1" label="appid" prop="appId" key="4">
        <a-input
            v-model.trim="form.appId"
            placeholder=""
            allowClear
          />
      </a-form-model-item>
      <a-form-model-item v-if="form.jumpWayId!=4 && form.jumpWayId!=5" label="落地页" prop="landIngPage" key="5">
        <a-input
            v-model.trim="form.landIngPage"
            :placeholder="landIngPagePlaceholder"
            allowClear
          />
      </a-form-model-item>
      <!-- v-if="form.topicId && form.jumpWayId == 5" -->
      <a-form-model-item  label="图片" required key="6">
        <JImageUpload :isMove="false" :uploadParams="getUploadParams()"  :isMultiple="true" :fileSize="10" :number="1" :accept="'image/*'" @fileChange="fileImageChange" v-model="imageList"></JImageUpload>
        <div>注：请按照我们的图片建议尺寸上传图片（开屏弹窗广告为780-1110px；瀑布流广告位为504-765px），支持PNG, JPG和GIF格式，大小不超过1M</div>
      </a-form-model-item>
      <a-form-model-item label="排序值" prop="sorting">
        <a-input-number v-model="form.sorting" :min="0" :max="999"  /> 数值越小越靠前，限制999以内的数字
      </a-form-model-item>
      <a-form-model-item label="上线时间-下线时间" prop="time">
        <a-range-picker
          style="width:100%;"
          show-time
          valueFormat="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss"
          v-model="form.time"
        />
      </a-form-model-item>
      <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
        <a-button style="margin-right: 8px" @click="handleBack">取消</a-button>
        <a-button htmlType="submit" @click="handleSubmit" type="primary" >保存</a-button>
      </a-form-model-item>
    </a-form-model>
    <a-modal title="同一时段已有开屏弹窗广告" :visible="err1Visible" width="400px" okText="留在当前页" cancelText="去编辑原广告" :closable="false" @ok="err1Visible = false,spinning=false" @cancel="handleAddOrEditAd">
      <p>原开屏弹窗：{{details.title}}</p>
      <p>原开始时间：{{details.onlineTime}}</p>
      <p>原结束时间：{{details.offlineTime}}</p>
    </a-modal>
    <a-modal title="同一时段可展示广告数已达上限" :visible="err2Visible" width="400px" okText="留在当前页" cancelText="去编辑原广告" :closable="false" @ok="err2Visible = false,spinning=false" @cancel="handleAddOrEditAd">
      <a-table bordered size="small" :pagination="false" :rowKey="record => record.id" :columns="columns" :data-source="list"></a-table>
      <div>注：首页瀑布流广告位同时最多支持展示4个广告</div>
    </a-modal>
  </a-card>
  </a-spin>
</template>
<script>
  import JImageUpload from '../../components/JImageUpload'
  import { brandList } from '../../components/brandList.js'
  import { topicPage } from '@/api/micromall/communityContent'
  import { advertisingAddOrUpdate, advertisingDetail } from '@/api/micromall/communityMarketing'
  
  const columns = [
    {
      title: '原瀑布流广告',
      dataIndex: 'title',
      align: 'center'
    },
    {
      title: '开始时间',
      dataIndex: 'onlineTime',
      align: 'center'
    },
    {
      title: '结束时间',
      dataIndex: 'offlineTime',
      align: 'center'
    }
  ];
  export default {
    components: {
      JImageUpload
    },
    data() {
      return {
        id: this.$route.params.id,
        brandList,
        advertisingTypeList: [
          {
            name: '开屏弹窗',
            id: '1'
          },
          {
            name: '首页瀑布流',
            id: '2'
          },
          {
            name: '首页话题区',
            id: '3'
          }
        ],
        jumpWayList: [
          {
            name: '小程序路径',
            id: '1'
          },
          {
            name: '不跳转',
            id: '4'
          },
          {
            name: '自定义链接',
            id: '2'
          },
          {
            name: '视频号',
            id: '3'
          },
          {
            name: '话题',
            id: '5'
          }
        ],
        topicList: [],
        imageList: [],
        list: [],
        details: {},
        columns,
        err1Visible: false, // 开屏弹窗时段冲突弹窗内容
        err2Visible: false, // 同一时段可展示广告数已达上限
        spinning: false,
        form: {
          topicId: ''
        },
        rules: {
          weId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          advertisingTypeId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          jumpWayId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          topicId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          title: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          theCurrent: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          appId: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          landIngPage: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          sorting: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          time: [
            { required: true, message: '请选择', trigger: 'change' }
          ]
        }
      }
    },
    created() {
      this.getTopicPage()
      this.getDetails(this.$route.params.id)
    },
    computed: {
      landIngPagePlaceholder() {
        const jumpWayId = this.form.jumpWayId // 1.小程序路径 2.自定义链接 3.视频号
        let str = ''
        if (jumpWayId == 1) {
          str = '请保证使用/开头的小程序路径'
        } else if (jumpWayId == 2) {
          str = '请确保域名已添加为小程序业务域名，并且保证http开头'
        } else if (jumpWayId == 3) {
          str = '请填写视频号ID'
        }
        return str 
      }
    },
    mounted() {
    },
    beforeDestroy() {
    },
    methods: {
      adTypeChange(value) {
        if(value == 3) this.form.jumpWayId = '5'
        // this.$refs.rulesForm.validate()
      },

      jumpWayIdChange() {
        this.form.topicId = ''
        this.imageList = ''
      },

      // 话题
      topicChange(v) {
        const filterList = this.topicList.filter(e => v == e.id)
        this.imageList = filterList.length ? filterList[0].topicImage : []
      },

      // 获取话题列表
      getTopicPage() {
        const data = {
          pageNo: 1,
          pageSize: 1000,
          options: 1
        }
        topicPage(data).then(res => {
          if (res.code === 200) {
            const { records} = res.data
            this.topicList = records
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },
      
      // 获取详情
      getDetails(id) {
        if (id == 'null') return
        const data = {
          id
        }
        advertisingDetail(data).then(res => {
          if (res.code === 200) {
            const {image, onlineTime, offlineTime} = res.data
            this.form = {
              ...res.data,
              time: [onlineTime, offlineTime]
            }
            this.imageList = [image]
          } else {
            this.$message.error(res.msg || res.message)
          }
        }).catch(err => {
        })
      },

      getUploadParams() {
        return {
            actionUrl: 'https://jic.jnby.com/activity/market-act/common/upload/multipart',
            headers: {
              authorization: 'authorization-text'
            },
            uploadHost: 'https://img.bzhz.jnbygroup.com/'
          }
      },
      // 图片change
      fileImageChange(list) {
        this.form.image = list.length ? list[0].url : ''
      },

       // 编辑广告
      handleAddOrEditAd() {
        this.err2Visible = false
        this.err1Visible = false
        this.spinning = false
        this.$router.replace(`/micromall/community/marketingManagement/addOrEditAdvertisement/${this.list[0].id}`)
        this.getDetails(this.list[0].id)
      },

      // 确认同步
      handleSubmit() {
        this.$refs.rulesForm.validate(valid => {
          if (valid) {
            const {title, image, time, topicId, jumpWayId, landIngPage, theCurrent, appId, weId, advertisingTypeId} = this.form
             if (!image) {
              this.$message.error('请上传图片！')
              return
            }
            const weNameList = this.brandList.filter(e => e.weid == weId)
            const advertisingTypeList = this.advertisingTypeList.filter(e => e.id == advertisingTypeId)
            const jumpWayList = this.jumpWayList.filter(e => e.id == jumpWayId)
            const topicList = this.topicList.filter(e => e.id == topicId)
            const topicName = topicList.length ? topicList[0].topicName : ''
           // 1.小程序路径 2.自定义链接 3.视频号 4.不跳转 5.话题
            const data = {
              ...this.form,
              onlineTime: time[0],
              offlineTime: time[1],
              weName: weNameList.length ? weNameList[0].name : '',
              advertisingType: advertisingTypeList.length ? advertisingTypeList[0].name: '',
              jumpWay: jumpWayList.length ? jumpWayList[0].name : '',
              appId: jumpWayId == 1 && theCurrent == 1 ? appId : null,
              landIngPage: jumpWayId != 4 && jumpWayId != 5 ? landIngPage : null,
              theCurrent: jumpWayId == 1 ? theCurrent : null,
              topicId: jumpWayId == 5 ? topicId : null,
              title: jumpWayId == 5 ? topicName : title
            }
            this.spinning = true
            advertisingAddOrUpdate(data).then(res => {
              if (res.code === 200) {
                if (res.data.length) {
                  this.list = res.data
                  if (res.data.length > 1) {
                    this.err2Visible = true
                  } else {
                    this.details = res.data[0]
                    this.err1Visible = true
                  }
                } else {
                  this.$router.go(-1)
                }
              } else {
                this.spinning = false
                this.$message.error(res.msg || res.message)
              }
            }).catch(err => {
              this.spinning = false
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      },

      //返回
      handleBack() {
        this.$router.go(-1)
      },

      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      },
    }
  }
</script>
<style lang="less" scoped>

</style>
